package lex.dm.cluster;

import lex.dm.id3.ArrayDataSet;
import lex.dm.id3.IDataSet;

public class ClusterUtils {
	public static IDataSet kmeans(int[] k, IDataSet dataSet) {
		NumericClustering[] algors = new NumericClustering[k.length];
		for (int i = 0; i < k.length; i++)
			if (k[i] > 1)
				algors[i] = new NumericClustering(k[i]);
		return kmeans(algors, dataSet);
	}

	private static IDataSet kmeans(NumericClustering[] algors, IDataSet dataSet) {
		if (algors.length != dataSet.getColumnCount()) {
			System.err.println("cluster error: �㷨����������������");
			return null;
		}
		Object[][] data = dataSet.getData();
		int rowCount = dataSet.getRowCount();
		int columnCount = dataSet.getColumnCount();
		Number[] column = new Number[rowCount];
		for (int col = 0; col < columnCount; col++) {
			if (null != algors[col]) {
				for (int row = 0; row < rowCount; row++)
					column[row] = (Number) data[row][col];
				Object[] cluster = algors[col].cluster(column);
				for (int row = 0; row < rowCount; row++)
					data[row][col] = cluster[row];
			}
		}
		return new ArrayDataSet(data, attributes(dataSet), dataSet.getClassAttributeIndex());
	}

	private static String[] attributes(IDataSet ds) {
		String[] attr = new String[ds.getAttributeCount()];
		for (int i = 0; i < attr.length; i++)
			attr[i] = ds.getAttribute(i);
		return attr;
	}
}
